package com.hangyutech.strelitzia.modules.controller;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.hangyutech.strelitzia.utils.FileUtil;
import com.hangyutech.strelitzia.vo.HttpResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * OSS上传主类方法
 * @Author sgl
 * @Date 2018-05-15 14:04
 */
@RestController
@RequestMapping("upload")
@CrossOrigin
@Api(description = "上传")
public class UploadController {
    private static final Logger LOGGER = LoggerFactory.getLogger(UploadController.class);

    private String accessId = "11"; // 请填写您的AccessKeyId。
    private String accessKey = "11"; // 请填写您的AccessKeySecret。
    private String endpoint = "oss-cn-qingdao.aliyuncs.com"; // 请填写您的 endpoint。
    private String bucket = "wicon"; // 请填写您的 bucketname 。
    private String host = "https://" + bucket + "." + endpoint; // host的格式为 bucketname.endpoint
    // callbackUrl为 上传回调服务器的URL，请将下面的IP和Port配置为您自己的真实信息。
    private String dir = "strelitzia/"; // 用户上传文件时指定的前缀。
    private String encodedPolicy = "";
    private String postSignature = "";

    @PostMapping("oss")
    @ApiOperation(value = "上传文件并转存到OSS")
    @ResponseBody
    public HttpResult upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return HttpResult.error().message("上传失败");
        }

        Date dNow = new Date();
        SimpleDateFormat month = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat nowTime = new SimpleDateFormat("hhmmss");
        String newFileName = month.format(dNow);
        String fileName = nowTime.format(dNow)
                + "-"
                + String.format("%04d", new Random().nextInt(9999))
                + "."
                + FileUtil.getExtendName(file.getOriginalFilename());
        String localFileFullPath = "/tmp/" + fileName;
        File localFile = new File(localFileFullPath);
        try {
            file.transferTo(localFile);

            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessId, accessKey);
            // 上传文件流。
            InputStream inputStream = null;
            inputStream = new FileInputStream(localFileFullPath);
            ossClient.putObject(bucket, dir + "uploads/" + newFileName + "/" + fileName, inputStream);
            // 删除文件并关闭OSSClient。
            localFile.delete();
            ossClient.shutdown();

            return HttpResult.ok()
                    .data("url", host + "/" + dir + "uploads/" + newFileName + "/" + fileName)
                    .message("上传成功");
        } catch (IOException e) {
            LOGGER.error(e.toString(), e);
        }
        return HttpResult.error().message("上传失败");
    }


    @ApiOperation(value = "获取OSS的授权信息")
    @GetMapping("ossauth")
    public HttpResult ossAuth() {
        Map<String, String> respMap = new LinkedHashMap<String, String>();
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessId, accessKey);
        long expireTime = 60 * 60 * 10;
        long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
        try {
            Date expiration = new Date(expireEndTime);
            // PostObject请求最大可支持的文件大小为5 GB，即CONTENT_LENGTH_RANGE为5*1024*1024*1024。
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            encodedPolicy = BinaryUtil.toBase64String(binaryData);
            postSignature = ossClient.calculatePostSignature(postPolicy);

//            respMap.put("accessid", accessId);
//            respMap.put("policy", encodedPolicy);
//            respMap.put("signature", postSignature);
//            respMap.put("dir", dir);
//            respMap.put("host", host);
//            respMap.put("expire", String.valueOf(expireEndTime / 1000));
//             respMap.put("expire", formatISO8601Date(expiration));
//            System.out.println(respMap);

//            JSONObject jasonCallback = new JSONObject();
//            jasonCallback.put("callbackUrl", callbackUrl);
//            jasonCallback.put("callbackBody",
//                    "filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}");
//            jasonCallback.put("callbackBodyType", "application/x-www-form-urlencoded");
//            String base64CallbackBody = BinaryUtil.toBase64String(jasonCallback.toString().getBytes());
//            respMap.put("callback", base64CallbackBody);

//            JSONObject ja1 = JSONObject.fromObject(respMap);
//            // System.out.println(ja1.toString());
//            response.setHeader("Access-Control-Allow-Origin", "*");
//            response.setHeader("Access-Control-Allow-Methods", "GET, POST");
//            response(request, response, ja1.toString());

        } catch (Exception e) {
            // Assert.fail(e.getMessage());
            System.out.println(e.getMessage());
        } finally {
            ossClient.shutdown();
        }

        return HttpResult.ok()
                .data("accessId", accessId)
                .data("policy", encodedPolicy)
                .data("signature", postSignature)
                .data("dir", dir)
                .data("host", host)
                .data("expire", String.valueOf(expireEndTime / 1000))
                .message("查询列表成功");
    }


}